package com.ssmk.module.shoppingcar;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.retrofitlibrary.BaseObserBean2;
import com.example.retrofitlibrary.RetrofitClientUtlis;
import com.google.gson.Gson;
import com.pingplusplus.android.Pingpp;
import com.ssmk.R;
import com.ssmk.base.MVPBaseActivity;
import com.ssmk.module.merchant.Data;
import com.ssmk.module.shoppingcar.adapter.OrderAdapter;
import com.ssmk.module.shoppingcar.adapter.OrderAdapter2;
import com.ssmk.module.shoppingcar.adapter.OrderCartAdapter;
import com.ssmk.module.shoppingcar.bean.CartSureOrderBean;
import com.ssmk.module.shoppingcar.bean.LiJiBean;
import com.ssmk.module.shoppingcar.bean.ShopsOrderBean;
import com.ssmk.module.shoppingcar.bean.SubmitOrderBean;
import com.ssmk.module.shoppingcar.bean.SureOrderBean;
import com.ssmk.url.Url;
import com.ssmk.utlis.GetCharge;
import com.ssmk.utlis.PopUtils;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

import static com.pingplusplus.android.Pingpp.REQUEST_CODE_PAYMENT;
import static com.umeng.socialize.utils.DeviceConfig.context;

public class OrderActivity extends MVPBaseActivity implements View.OnClickListener {

    @BindView(R.id.order_recycler)
    RecyclerView mOrderRecycler;
    @BindView(R.id.btn_submit_order)
    Button mBtnSubmitOrder;
    @BindView(R.id.top_iv_back)
    ImageView mTopIvBack;
    @BindView(R.id.top_tv_title)
    TextView mTopTvTitle;
    @BindView(R.id.should_money)
    TextView shouldMoney;
    @BindView(R.id.rlBottom)
    RelativeLayout rlBottom;
    @BindView(R.id.activity_order)
    RelativeLayout activityOrder;
    @BindView(R.id.order_should_money)
    TextView orderShouldMoney;
    //private String body1 = "{\"deliveryName\":\"张三\",\"deliveryTel\":\"13452639857\",\"addressDetail\":\"收货地址-北京顺义\",\"totalFreight\":0,\"totalPrice\":500,\"payMode\":\"微信\",\"commodityAndSellerList\":[{\"sellerId\":103,\"sellerName\":\"森马\",\"commodityInfoList\":[{\"goodsId\":\"42A34D35A56445AD8244B413CF397935\",\"cartId\":\"\",\"goodsName\":\"商品一\",\"goodsCode\":\"1503195253850755\",\"skuId\":\"088b12ba009b39eaa5b1efa1cf291da1\",\"goodsFormatId\":\"26\",\"sizeNumberId\":\"10\",\"goodsPrice\":145,\"freight\":0,\"purchaseSize\":2}]},{\"sellerId\":110,\"sellerName\":\"美特斯邦威\",\"commodityInfoList\":[{\"goodsId\":\"63CB12170FA1495790B9329F7123678B\",\"cartId\":\"\",\"goodsName\":\"商品二\",\"goodsCode\":\"1503145083894922\",\"skuId\":\"87fc31d71c23cf6c4969b1fe941614fd\",\"goodsFormatId\":\"13\",\"sizeNumberId\":\"10\",\"goodsPrice\":210,\"freight\":0,\"purchaseSize\":1}]}]}";
    private String sBean;
    private PopupWindow mPopupWindow;
    private LinearLayout mPay_zhifubao;
    private LinearLayout mPay_wx;

    private static String YOUR_URL = "http://218.244.151.190/demo/charge";
    public static final String CHARGE_URL = YOUR_URL;
    public static final boolean LIVEMODE = false;

    /**
     * 微信支付渠道
     */
    private static final String CHANNEL_WECHAT = "wx";

    /**
     * 支付宝支付渠道
     */
    private static final String CHANNEL_ALIPAY = "alipay";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        mBtnSubmitOrder.setOnClickListener(this);
        mTopIvBack.setOnClickListener(this);
    }

    @Override
    protected void initview() {
        Resources res = this.getResources();
        //确认订单
        String title = res.getString(R.string.affirm_order);
        mTopTvTitle.setText(title);



    }

    @Override
    protected void initdata() {
        Gson gson = new Gson();
        LiJiBean lijibean1 = Data.liJiBean;
        if (lijibean1 == null) {
            ArrayList<ShopsOrderBean> shopsList1 = Data.shopsOrderBeen;
            //最外层对象
            CartSureOrderBean cartSureOrderBean = new CartSureOrderBean();
            //第二层对象
            CartSureOrderBean.CommodityAndSellerListBean dd1 = new CartSureOrderBean.CommodityAndSellerListBean();
            //第二层集合
            ArrayList<CartSureOrderBean.CommodityAndSellerListBean> commodityAndSellerListBeen1 = new ArrayList<>();
            //第三层对象
            CartSureOrderBean.CommodityAndSellerListBean.CommodityInfoListBean aa1 = new CartSureOrderBean.CommodityAndSellerListBean.CommodityInfoListBean();
            //第三层集合
            List<CartSureOrderBean.CommodityAndSellerListBean.CommodityInfoListBean> lists1 = new ArrayList<>();

            //遍历传过来的集合
            for (ShopsOrderBean cc : shopsList1) {
                String sellerName = cc.getSellerName();
                int sellerId = cc.getSellerId();

                //给第二层对象里面的两个属性赋值
                dd1.setSellerId(sellerId);
                dd1.setSellerName(sellerName);

                //得到第二层对象的一个集合字段
                List<ShopsOrderBean.CommodityInfoListBean> commodityInfoList = cc.getCommodityInfoList();
                //遍历这个集合，给集合里面的多个对象里面的属性赋值
                for (ShopsOrderBean.CommodityInfoListBean ee : commodityInfoList) {
                    //取出每个对象里面的字段数据
                    int goodsPrice = ee.getGoodsPrice();
                    String cartId = ee.getCartId();
                    int freight = ee.getFreight();
                    String goodsCode = ee.getGoodsCode();
                    String goodsFormatId = ee.getGoodsFormatId();
                    String goodsId = ee.getGoodsId();
                    String goodsName = ee.getGoodsName();
                    int purchaseSize = ee.getPurchaseSize();
                    String sizeNumberId = ee.getSizeNumberId();
                    int a3 = purchaseSize;
                    int v3 = goodsPrice;
                    // DecimalFormat myformat=new DecimalFormat("0.00");
                    //String s = myformat.format(v);
                    int v4 = (a3 * v3);
                    int count = lists1.size();
                    int totalPrice = (v4 * count);
                    //循环遍历把每个对象里面的字段赋值
                    aa1.setGoodsPrice(v3);
                    aa1.setFreight(0);

                    cartSureOrderBean.setTotalPrice(v4);
                    aa1.setGoodsCode(goodsCode);
                    aa1.setGoodsName(goodsName);
                    aa1.setPurchaseSize(purchaseSize);
                    aa1.setSizeNumberId(sizeNumberId);
                    aa1.setGoodsFormatId(goodsFormatId);
                    aa1.setGoodsId(goodsId);
                    aa1.setCartId("");
                    //循环添加每一个对象到第三层集合里面
                    lists1.add(aa1);
                }
                //把第二层对象里面的集合字段设置数据
                dd1.setCommodityInfoList(lists1);
                //把第二层集合设置数据
                commodityAndSellerListBeen1.add(dd1);
            }
            cartSureOrderBean.setCommodityAndSellerList(commodityAndSellerListBeen1);
            //TODO 设置收货地址信息
            cartSureOrderBean.setCommodityAndSellerList(commodityAndSellerListBeen1);
            cartSureOrderBean.setDeliveryName("");
            cartSureOrderBean.setDeliveryTel("");
            cartSureOrderBean.setAddressDetail("");
            cartSureOrderBean.setTotalFreight(0);
            cartSureOrderBean.setPayMode("微信");

            this.sBean = gson.toJson(cartSureOrderBean);
            mOrderRecycler.setLayoutManager(new LinearLayoutManager(this));
            OrderCartAdapter adapter = new OrderCartAdapter(this);
            adapter.setData(shopsList1);
            adapter.setOnItemClickLitener(new OrderAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, int position) {

                }
            });

        } else {

            SureOrderBean sureOrderBean = new SureOrderBean();
            sureOrderBean.setDeliveryName("");
            sureOrderBean.setDeliveryTel("");
            sureOrderBean.setAddressDetail("");
            sureOrderBean.setTotalFreight(0);
            sureOrderBean.setPayMode("微信");

            ArrayList<SureOrderBean.CommodityAndSellerListBean> commodityAndSellerListBeen = new ArrayList<>();
            SureOrderBean.CommodityAndSellerListBean dd = new SureOrderBean.CommodityAndSellerListBean();
            dd.setSellerId(Integer.parseInt(lijibean1.getCommodityAndSellerList().get(0).getSellerid()));
            dd.setSellerName(lijibean1.getCommodityAndSellerList().get(0).getSellerName());

            //商品数量
            int a = Integer.parseInt(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getPurchaseSize());
            //商品单价
            double v = Double.parseDouble(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsPrice());

            SureOrderBean.CommodityAndSellerListBean.CommodityInfoListBean aa = new SureOrderBean.CommodityAndSellerListBean.CommodityInfoListBean();

            List<SureOrderBean.CommodityAndSellerListBean.CommodityInfoListBean> lists = new ArrayList<>();
            // DecimalFormat myformat=new DecimalFormat("0.00");
            //String s = myformat.format(v);

            double v1 = a * v;
            int v2 = (int) v1;
            aa.setGoodsPrice(v2);
            aa.setFreight(0);
            sureOrderBean.setTotalPrice(v2 * a);
            aa.setGoodsCode(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsCode());
            aa.setGoodsName(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsName());
            aa.setPurchaseSize(Integer.parseInt(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getPurchaseSize()));

            if (lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getSizeNumberId() == null) {
                aa.setSizeNumberId("");
            } else {
                aa.setSizeNumberId(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getSizeNumberId());
            }
            // aa.setSkuId(lijibean.getCommodityAndSellerList().get(0).getCommodityInfoList().getSkuId());
            if (lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsFormatId() == null) {
                aa.setGoodsFormatId("");
            } else {
                aa.setGoodsFormatId(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsFormatId());
            }
            aa.setGoodsFormatId(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsFormatId());
            aa.setGoodsId(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsId());
            aa.setCartId("");
            lists.add(aa);

            dd.setCommodityInfoList(lists);
            commodityAndSellerListBeen.add(dd);
            sureOrderBean.setCommodityAndSellerList(commodityAndSellerListBeen);

            this.sBean = gson.toJson(sureOrderBean);

            orderShouldMoney.setText(lijibean1.getCommodityAndSellerList().get(0).getCommodityInfoList().getGoodsPrice());
            mOrderRecycler.setLayoutManager(new LinearLayoutManager(this));
            OrderAdapter adapter = new OrderAdapter(this);

            //
            boolean shoudao = getIntent().getBooleanExtra("shoudao", false);
            String[] ewq = {"你还没有添加收货信息","","点击添加收获信息"};
            String[] sss = getIntent().getStringArrayExtra("shuju");
            mOrderRecycler.setAdapter(adapter);
            if (shoudao) {
                SharedPreferences sp = getSharedPreferences("sp", MODE_PRIVATE);
                ArrayList<String> list2 = new ArrayList<String>();
                if (sss!=null){
                list2.add("收货人："+sss[0]);
                list2.add("手机："+sss[1]);
                list2.add("地址："+sss[2]);
                }else{
                    list2.add(ewq[0]);
                    list2.add(ewq[1]);
                    list2.add(ewq[2]);
                }
                OrderAdapter2 orderAdapter2 = new OrderAdapter2(this, list2);
                mOrderRecycler.setAdapter(orderAdapter2);
                orderAdapter2.notifyDataSetChanged();
            }
            adapter.setOnItemClickLitener(new OrderAdapter.OnItemClickLitener() {
                @Override
                public void onItemClick(View view, int position) {

                    //TODO 跳转到地址页面
                    Intent intent = new Intent(OrderActivity.this, AddressActivity.class);
                    startActivity(intent);
                }
            });
        }

    }

    @Override
    protected int layoutRes() {

        return R.layout.activity_order;

    }

    @Override
    public void UpData(Object o) {

    }


    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            //返回键
            case R.id.top_iv_back:
                finish();
                break;
            //点击提交订单
            case R.id.btn_submit_order:
                showPopuptWindow(v);

                break;
        }
    }


    private void showPopuptWindow(View view) {
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        View popupWindow_view = PopUtils.getPopView(this);
        PopupWindow popUpWindow = PopUtils.getPopUpWindow(popupWindow_view);
        PopUtils.showPop(this, view, popUpWindow);//弹出pop

        mPay_zhifubao = (LinearLayout) popupWindow_view.findViewById(R.id.pay_zhifubao);
        mPay_wx = (LinearLayout) popupWindow_view.findViewById(R.id.pay_wx);

        mPay_zhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(OrderActivity.this, "支付宝", Toast.LENGTH_SHORT).show();
                selectedPay(CHANNEL_ALIPAY);
            }
        });
        mPay_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(OrderActivity.this, "微信", Toast.LENGTH_SHORT).show();
                selectedPay(CHANNEL_WECHAT);
            }
        });
    }

    //选择支付方式提交订单--weixin
    private void selectedPay(final String channel) {
        Map<String, String> map1 = new HashMap<>();
        map1.put("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjI1MiwicHdkIjoiZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2UiLCJpYXQiOjE1MDA0MzYyNzg1MDIsImV4dCI6MTUwMTA0MTA3ODUwMn0.ws2972b0tfqUWbiluxEEtv_2mbAjZzk3k9lTFxyHIvA");
        map1.put("Content-Type", "application/json");
        RequestBody body = RequestBody.create(RetrofitClientUtlis.JSON, sBean);

        RetrofitClientUtlis.getInstance(this, Url.BASESUREORDER + "order/", map1)
                .createBaseApi()
                .executePostJson(
                        //Url.BASESUREORDER11,
                        "submitOrder.do",
                        body, new BaseObserBean2<SubmitOrderBean>(context, SubmitOrderBean.class) {
                            @Override
                            public void Next(SubmitOrderBean data) {
                                if (data.getCode() == 200) {
                                    Log.i("likaihu", "Next: " + data.getMsg());
                                    String replaceable = String.format("[%s, \\s.]",
                                            NumberFormat.getCurrencyInstance(Locale.CHINA).getCurrency().getSymbol(Locale.CHINA));
                                    String cleanString = orderShouldMoney.getText().toString().replaceAll(replaceable, "");
                                    int amount = Integer.valueOf(new BigDecimal(cleanString).toString());

                                    new PaymentTask().execute(new PaymentRequest(channel, amount));

                                    /*Intent intent = new Intent(OrderActivity.this, EvaluateActivity.class);
                                    startActivity(intent);*/
                                }

                            }
                        });

    }


    private class PaymentTask extends AsyncTask<PaymentRequest, Void, String> {

        @Override
        protected void onPreExecute() {
            //按键点击之后的禁用，防止重复点击
            mPay_zhifubao.setOnClickListener(null);
            mPay_wx.setOnClickListener(null);

        }

        @Override
        protected String doInBackground(PaymentRequest... pr) {

            PaymentRequest paymentRequest = pr[0];
            String data = null;
            try {
                JSONObject object = new JSONObject();
                object.put("channel", paymentRequest.channel);
                object.put("amount", paymentRequest.amount);
                object.put("livemode", paymentRequest.livemode);
                String json = object.toString();
                //向Your Ping++ Server SDK请求数据
                data = GetCharge.postJson(CHARGE_URL, json);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }

        /**
         * 获得服务端的charge，调用ping++ sdk。
         */
        @Override
        protected void onPostExecute(String data) {
            if (null == data) {
                showMsg("请求出错", "请检查URL", "URL无法获取charge");
                return;
            }
            Log.d("charge", data);

            //除QQ钱包外，其他渠道调起支付方式：
            //参数一：Activity  当前调起支付的Activity
            //参数二：data  获取到的charge或order的JSON字符串
            Pingpp.createPayment(OrderActivity.this, data);//data--->charge

            //QQ钱包调用方式
            //参数一：Activity  当前调起支付的Activity
            //参数二：data  获取到的charge或order的JSON字符串
            //参数三：“qwalletXXXXXXX”需与AndroidManifest.xml中的scheme值一致
            //Pingpp.createPayment(ClientSDKActivity.this, data, "qwalletXXXXXXX");
        }

    }


    class PaymentRequest {
        String channel;
        int amount;
        boolean livemode;

        public PaymentRequest(String channel, int amount) {
            this.channel = channel;
            this.amount = amount;
            this.livemode = LIVEMODE;
        }
    }

    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null != msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null != msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderActivity.this);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", null);
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //支付页面返回处理
        if (requestCode == REQUEST_CODE_PAYMENT) {
            String pay_result = data.getExtras().getString("pay_result");
                /* 处理返回值
             * "success" - 支付成功
             * "fail"    - 支付失败
             * "cancel"  - 取消支付
             * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
             */
            String error_msg = data.getExtras().getString("error_msg");//错误信息
            String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
            showMsg(pay_result, error_msg, extraMsg);

        }
    }
}
